<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/26
 * Time: 15:15
 */

namespace app\admin\logic;


use app\common\utils\PHPExcelUtils;
use PHPExcel_Cell;
use PHPExcel_IOFactory;
use think\Db;
use think\Exception;
use think\Log;

class TopicLogic
{
    /**
     * 添加题目
     * @param $data
     * @return array status 0失败 1成功
     */
    public function add($data){
        $topic = $data['topic'];

        $result = $this->check($data);
        if($result['status'] !=1){
            return $result;
        }
        Db::startTrans();
        try{
            $topic_info = model('Topic')->create($topic);
            if(!$topic_info){
                Db::rollback();//回滚
                return ['status'=>0,'error'=>'添加失败'];
            }
            $this->addOptionItems($data,$topic_info['id']);
            Db::commit();
            return ['status'=>1];
        }catch (Exception $e){
            Db::rollback();//回滚
            return ['status'=>0,'error'=>$e->getMessage()];
        }
    }

    /**
     * 修改题目
     * @param $data
     * @return array status 0失败 1成功
     */
    public function edit($data){
        $result = $this->check($data);
        if($result['status'] !=1){
            return $result;
        }
        $topic = $data['topic'];
        Db::startTrans();
        try{
            DB::name('Topic')->where(array('id'=> $topic['id']))->update($topic);
            $this->updateOptionItems($data, $topic['id']);
            Db::commit();
            return ['status'=>1];
        }catch (Exception $e){
            Db::rollback();//回滚
            return ['status'=>0,'error'=>$e->getMessage()];
        }
    }

    /**
     * 添加多个选项
     * @param $data
     * @param $topic_id
     */
    private function addOptionItems($data,$topic_id){
        $option_items = $data['radio_items'];
        $option_ids = '';
        foreach ($option_items as $key=>$value){
            $option_id = $this->addOptionItem($value,$topic_id);
            Log::log('correct:'.$value['correct']);
            if($value['correct'] == 1){
                $option_ids =$option_id;
            }
        }
        $option_ids = rtrim($option_ids, ',');
        Db::name('Topic')->where(['id'=>$topic_id])->setField('answer',$option_ids);
    }

    private function updateOptionItems($data,$topic_id){
        $topic = $data['topic'];
        $option_items = $data['radio_items'];
        //获取题目原来的选项
        $original_option_items = model('Option')->where(array('topic_id'=>$topic['id']))->select();
        $option_items_length = count($option_items);
        $original_option_items_length = count($original_option_items);
        if($option_items_length != $original_option_items_length && $original_option_items_length > $option_items_length){
            //删除
            $result = $this->updateOption($option_items,$original_option_items,$topic_id);
            $option_ids = $result['option_ids'];
            $update_option_ids = $result['update_option_ids'];
            //删除多的
            model('Option')
                ->where(array('topic_id'=>$topic_id))
                ->where('id','not in',$update_option_ids)
                ->delete();
        }else{
            $result = $this->updateOption($option_items,$original_option_items,$topic_id);
            $option_ids = $result['option_ids'];
        }
        $option_ids = rtrim($option_ids, ',');
        Db::name('Topic')->where(['id'=>$topic_id])->setField('answer',$option_ids);
    }

    private function updateOption($option_items,$original_option_items,$topic_id){
        $option_ids = '';//答案
        $update_option_ids = [];//更新的选项
        foreach ($option_items as $key=>$value){
            if($key >= count($original_option_items)){
                $option_id = $this->addOptionItem($value,$topic_id);
            }else{
                $option_id = $original_option_items[$key]['id'];
                $update_option_ids[]=$option_id;
                $this->updateOptionItem($value,$topic_id,$option_id);
            }
            Log::log('correct:'.$value['correct']);
            if($value['correct'] == 1){
                $option_ids = $option_id;
            }
        }
        return ['option_ids'=>$option_ids,'update_option_ids'=>$update_option_ids];
    }

    private function updateOptionItem($option_item,$topic_id,$option_id){
        $option['topic_id'] = $topic_id;
        $option['is_correct'] = $option_item['correct'];
        $option['content'] = $option_item['content'];
        model('Option')->where(array('id'=>$option_id))->update($option);
    }

    /**
     * 添加单个选项
     * @param $option_item
     * @param $topic_id
     * @return int|string
     */
    private function addOptionItem($option_item,$topic_id){
        $option['topic_id'] = $topic_id;
        $option['is_correct'] = $option_item['correct'];
        $option['content'] = $option_item['content'];
        $option = model('Option')->create($option);

        return $option['id'];
    }

    /**
     * 检查数据
     * @param $data 2必须要有一个正确选项 3正确选项只能有一个 4选项内容不能为空
     * @return mixed
     */
    private function check($data){
        if( !isset($data['radio_items'])){
            return array('status'=>2,'msg'=>'选项内容不能为空');
        }
        //单选题
        $radio_items = $data['radio_items'];
        $correct_count = 0;
        foreach ($radio_items as $key=>$value){
            if($value['content'] == ''){
                return array('status'=>2,'msg'=>'选项内容不能为空');
            }
            if($value['correct'] == 1){
                $correct_count++;
            }
        }
        if($correct_count ==0){
            return array('status'=>2,'msg'=>'必须要有一个正确选项');
        }
        if($correct_count > 1){
            return array('status'=>2,'msg'=>'正确选项只能有一个');
        }
        if($correct_count == 1){
            return array('status'=>1);
        }
        return array('status'=>1);
    }

    /**
     * 导入
     * @param $file_name string 文件名
     * @return array
     */
    public function import($file_name){
        Db::startTrans();
        try {
            $utils = new PHPExcelUtils();
            $data = $utils->read($file_name);
            if (!$data) {
                return array('status' => 2, 'msg' => '读取数据失败！');
            }
            foreach ($data as $key=>$row){
                if(count($row) != 9){
                    continue;
                }
                $title = $row[0];
                $count = model('Topic')->where(array('title'=>$title))->count();
                if($count > 0){
                    continue;
                }
                $category_name = $row[1];
                $sub_category_name = $row[2];
                $choice_index = $row[3] - 1;
                $category_id_array = $this->getCategoryId($category_name,$sub_category_name);
                $add_topic['title'] = $title;
                $add_topic['category_id'] = $category_id_array['category_id'];
                $add_topic['sub_category_id'] = $category_id_array['sub_category_id'];
                $add_topic['is_use'] = 0;
                $add_topic['grade'] = $row[8];
                $topic = model('Topic')->create($add_topic);
//                return array('status'=>0,'error'=>$row[0]);
                $this->addOption($row,$choice_index,$topic['id']);
            }
            Db::commit();
            return array('status'=>1);
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    public function importNew($filename, $encode = 'utf-8')
    {
        ini_set("memory_limit", "255M");
        Db::startTrans();
        try {
            setlocale(LC_ALL, 'zh_CN');
            $objReader = PHPExcel_IOFactory::createReader('Excel5');//读取xls
            if (!$objReader->canRead($filename)) {
                //读取xlsx
                $objReader = PHPExcel_IOFactory::createReader('Excel2007');
                if (!$objReader->canRead($filename)) {
                    return array('status'=>2,'msg'=>'无法读取文件');
                }
            }
            $objPHPExcel = $objReader->load($filename);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $highestColumn = $objWorksheet->getHighestColumn();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
            $excelData = [];
            for ($row = 2; $row <= $highestRow; $row++) {
                $value = (string)$objWorksheet->getCellByColumnAndRow(0, $row)->getValue();
                if ($value == '') {
                    continue;
                }
                $excelData[$row] = [];
                for ($col = 1; $col < $highestColumnIndex; $col++) {
                    $value = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
//                if($col == 8){//指定H列为时间所在列
//                    $value = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));
//                }
                    if (!is_numeric($value) && $value != '') {
//                    $value = iconv('utf-8', 'gbk//ignore', $value);//解决中文乱码
                        $value = mb_convert_encoding($value, 'utf-8');
                    }
                    $excelData[$row][] = $value;
                }
                if ($row % 500 == 0) {
                    $this->importData($excelData);
                    $excelData = null;
                    $excelData = [];
                }
            }
            Db::commit();
            return array('status'=>1);
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    private function importData($data){
        foreach ($data as $key=>$row){
            if($key % 10 == 0){
                Log::write(count($row));
            }
            if(count($row) != 14){
                continue;
            }

            $title = $row[2];//题目
            $count = model('Topic')->where(array('title'=>$title))->count();
            if($count > 0){
                continue;
            }
            $category_name = $row[11];//分类名
            $choice_index = ord($row[12]) - 65;
            $category_id_array = $this->getCategoryIdNew($category_name);
            if($category_id_array['status'] == 0){
                continue;
            }
            $add_topic['title'] = $title;
            $add_topic['category_id'] = $category_id_array['category_id'];
            $add_topic['sub_category_id'] = $category_id_array['sub_category_id'];
            $add_topic['is_use'] = 0;
            $add_topic['grade'] = $row[13] - 1;
            $option_num = $row[3];
            $topic = model('Topic')->create($add_topic);
//                return array('status'=>0,'error'=>$row[0]);
            $this->addOptionNew($row,$choice_index,$topic['id'],$option_num);
        }
    }

    private function addOptionNew($row,$choice_index,$topic_id,$option_num){
        $option = [];
        for ($i=0;$i<$option_num;$i++){
            $option[$i] = $row[4 + $i];
        }
        $correct_option_id = 0;
        $add_option['topic_id'] = $topic_id;
        foreach ($option as $key=>$value){
            $add_option['content'] = $value;
            if($choice_index == $key){
                $add_option['is_correct'] = 1;
                $option_obj = model('Option')->create($add_option);
                $correct_option_id = $option_obj['id'];
            }else{
                $add_option['is_correct'] = 0;
                model('Option')->insert($add_option);
            }
        }
        model('Topic')->where(array('id'=>$topic_id))->setField('answer',$correct_option_id);
    }

    private function getCategoryIdNew($category_name){
        $map['parent_id'] = array('neq',0);
        $map['name'] = $category_name;
        $category = model('Category')->where($map)->find();
        if($category){
            return ['status'=>1,'category_id'=>$category['parent_id'],'sub_category_id'=>$category['id']];
        }else{
            return ['status'=>0];
        }
    }

    /**
     * 添加选项
     * @param $row
     * @param $choice_index
     * @param $topic_id
     */
    private function addOption($row,$choice_index,$topic_id){
        $option = [];
        $option[0] = $row[4];
        $option[1] = $row[5];
        $option[2] = $row[6];
        $option[3] = $row[7];
        $correct_option_id = 0;
        $add_option['topic_id'] = $topic_id;
        foreach ($option as $key=>$value){
            $add_option['content'] = $value;
            if($choice_index == $key){
                $add_option['is_correct'] = 1;
                $option_obj = model('Option')->create($add_option);
                $correct_option_id = $option_obj['id'];
            }else{
                $add_option['is_correct'] = 0;
                model('Option')->insert($add_option);
            }
        }
        model('Topic')->where(array('id'=>$topic_id))->setField('answer',$correct_option_id);
    }

    /**
     * 根据名称获取类别和子类别id
     * @param $category_name
     * @param $sub_category_name
     * @return array
     */
    private function getCategoryId($category_name,$sub_category_name){
        $map['parent_id'] = 0;
        $map['name'] = $category_name;
        $category = model('Category')->where($map)->find();
        if(!$category){
            $add_category['parent_id'] = 0;
            $add_category['name'] = $category_name;
            $category = model('Category')->create($add_category);
        }
        $map['parent_id'] = $category['id'];
        $map['name'] = $sub_category_name;
        $sub_category = model('Category')->where($map)->find();
        if(!$sub_category){
            $add_sub_category['parent_id'] = $category['id'];
            $add_sub_category['name'] = $sub_category_name;
            $sub_category = model('Category')->create($add_sub_category);
        }
        return ['category_id'=>$category['id'],'sub_category_id'=>$sub_category['id']];
    }

}